#!/usr/bin/env python3

import argparse
import os
import subprocess

def command():
    parser = argparse.ArgumentParser(description='Build go project')
    parser.add_argument('-s', '--system', help='cross compiling target OS, default linux. (e.g. linux/windows)', default='linux', choices=['linux','windows'])
    parser.add_argument('-a', '--arch', help='cross compiling target arch, default amd64. (e.g. 386/amd64)', default='amd64', choices=['386','amd64'])
    parser.add_argument('-r', '--release', help='build release version, no symbol table, no gdb', action='store_true')
    parser.add_argument('-l', '--level', help='setup default log level, default debug. (e.g. debug/info/warning/error)', default='', choices=['debug','info','warning','error'])
    parser.add_argument('-o', '--out', help='specify the output directory', metavar='<dir>', default='')
    return parser.parse_args()


class Build:
    def __init__(self, args):
        self.args = args
        self.out_dir = ''

    def _default_value(self, value, def_val):
        if not value:
            return def_val
        return value

    def _cmd(self) -> str:
        cmd = ['go', 'build']
        ld_cmd = []
        if self.args.release:
            ld_cmd.append('-w')
            ld_cmd.append('-s')
        if self.args.level:
            ld_cmd.append('-X')
            ld_cmd.append('main.buildLogLevel=' + self.args.level)

        if len(ld_cmd) > 0:
            cmd.append('-ldflags')
            cmd.append('\'' + ' '.join(ld_cmd) + '\'')

        cmd.append('-o')
        if self.args.out:
            cmd.append(self.args.out)
        else:
            cmd.append(os.path.join(os.getcwd(), 'out'))
        return ' '.join(cmd)


    def exec(self):
        self.out_dir = self._default_value(self.args.out, os.path.join(os.getcwd(), 'out'))

        sub_env = os.environ.copy()
        sub_env['GOOS'] = self.args.system
        sub_env['GOARCH'] = self.args.arch

        subprocess.run(self._cmd(), shell=True, env=sub_env)



if __name__ == '__main__':
    args = command()
    if args:
        Build(args).exec()
